package com.fwj.core.common.config;

import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.core.common.model.ResponseEnum;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @Author: fwj
 * @Data: 2022/4/10 11:42
 * @Version 1.0
 * @Description:
 */

@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseDTO MethodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()){
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            return new ResponseDTO().fail(ResponseEnum.MISS_PARAMETER.getCode(),defaultMessage);
        } else {
            return new ResponseDTO().fail();
        }
    }

    @ExceptionHandler(BindException.class)
    public ResponseDTO BindException(BindException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()){
            String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
            return new ResponseDTO().fail(ResponseEnum.MISS_PARAMETER.getCode(),defaultMessage);
        } else {
            return new ResponseDTO().fail();
        }
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseDTO ConstraintViolationException(ConstraintViolationException exception) {
        return new ResponseDTO().fail();
    }


    @ExceptionHandler(CommonException.class)
    public ResponseDTO CommonException(CommonException e){
        return new ResponseDTO().fail(e.getResponseEnum());
    }

}
